package com.zkjl.protect_business.utils;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IORuntimeException;
import cn.hutool.poi.excel.ExcelReader;
import com.zkjl.protect_business.common.BaseException;
import com.zkjl.protect_business.entity.DocField;
import org.junit.platform.commons.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.zkjl.protect_business.common.Status.IO_ERROR;

public class ExcelUtil extends cn.hutool.poi.excel.ExcelUtil {

    /**
     * 解析excel
     *
     * @param file
     * @return
     * @throws IOException
     */
    public static List<Map<String, Object>> parsing(File file, Integer index) throws IOException {

        List<Map<String, Object>> maps = null;
        try {
            BufferedInputStream inputStream = FileUtil.getInputStream(file);

            ExcelReader reader = getReader(inputStream);
            maps = reader.read(index,index,Integer.MAX_VALUE);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException(IO_ERROR.getCode(), "文件格式可能已损坏，请确认后重试！", e.getMessage());
        }

        return maps;

    }


    /**
     * 解析Excel字段
     * @param multipartFile
     * @return
     * @throws IOException
     */
    public static List<DocField> parsingField(MultipartFile multipartFile) throws IOException {

        InputStream inputStream = multipartFile.getInputStream();

        ExcelReader reader = getReader(inputStream);

        List<List<Object>> read = reader.read();


        List<Object> titles = null;
        int index = 0;  //标题所在行
        //有表头的，合并过单元格之后的数据都是一样的,验证表头 合并超过2个单元格的就认定为表头
        for (int i = 0; i < read.size(); i++) {
            List<Object> objects = read.get(i);
            objects = objects.stream().filter(obj -> StringUtils.isNotBlank(obj + "") && obj != null).collect(Collectors.toList());

            Object o = objects.get(0);
            int frequency = Collections.frequency(objects, o);
            if (frequency > 1) {
                continue;
            }

            index = i;
            titles = objects;
            break;
        }


        List<DocField> docFields = new ArrayList<>();

        for (int i = 0; i < titles.size(); i++) {

            DocField docField = new DocField();
            docField.setKey(titles.get(i) + "");
            docField.setLocation(index + "," + i); //行号,列号

            docFields.add(docField);

        }
        return docFields;
    }




}
